// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import store from './store'
import App from './App'
import ElementUI from 'element-ui'
import BaiduMap from 'vue-baidu-map'
import router, {asyncRouterMap} from './router'
import http from './utils/http'
import 'element-ui/lib/theme-chalk/index.css'
import './assets/iconfont/iconfont.css'

Vue.prototype.$HTTP = http

Vue.use(BaiduMap, {
  ak: 'ZY7aIbSlkRGU1m5tQlopvIVxRtvKCi0M'
})

Vue.use(ElementUI)
Vue.config.productionTip = false

router.options.routes.push(asyncRouterMap[0])
router.addRoutes(router.options.routes)

// 导航钩子有3个参数
// to 即将要进入目标的路由对象
// from 当前导航即将要离开的路由对象
// next 调用方法后，才能进入下一个钩子
router.beforeEach((to, from, next) => {
  if (to.meta.title) window.document.title = to.meta.title
  if (to.path === '/login') {
    next()
  } else {
    if (store.state.global.loginUser) {
      next()
    } else {
      next({
        path: '/login'
      })
    }
  }
})

router.afterEach((to, from, next) => {
  window.scroll(0, 0)
})

// 自定义指令 图片加载失败时，加载默认图片
Vue.directive('default-img', async function (el, binding) {
  let defaultImgUrl = binding.value
  let imgUrl = el.getAttribute('src')
  if (defaultImgUrl) {
    let ifExist = await imgUrlValid(imgUrl)
    el.setAttribute('src', ifExist ? imgUrl : defaultImgUrl)
  }
})

let imgUrlValid = function (url) {
  return new Promise((resolve) => {
    let img = new Image()
    img.onload = function () {
      if (this.complete) {
        resolve(true)
        img = null
      }
    }
    img.onerror = function () {
      resolve(false)
      img = null
    }
    img.src = url
  })
}

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store, // 使用vuex
  components: { App },
  template: '<App/>'
})
